﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;

namespace WinEditor
{
    public partial class MainWin : Form
    {
        public ChromiumWebBrowser chromeBrowser;
        public const string HtmlTemplate = "<!DOCTYPE html><html><head><meta charset='utf-8'><title></title><style>.hljs{display:block;overflow-x:auto;padding:.5em;background:#f0f0f0}.hljs,.hljs-subst{color:#444}.hljs-comment{color:#888}.hljs-attribute,.hljs-doctag,.hljs-keyword,.hljs-meta-keyword,.hljs-name,.hljs-selector-tag{font-weight:700}.hljs-deletion,.hljs-number,.hljs-quote,.hljs-selector-class,.hljs-selector-id,.hljs-string,.hljs-template-tag,.hljs-type{color:#800}.hljs-section,.hljs-title{color:#800;font-weight:700}.hljs-link,.hljs-regexp,.hljs-selector-attr,.hljs-selector-pseudo,.hljs-symbol,.hljs-template-variable,.hljs-variable{color:#bc6060}.hljs-literal{color:#78a960}.hljs-addition,.hljs-built_in,.hljs-bullet,.hljs-code{color:#397300}.hljs-meta{color:#1f7199}.hljs-meta-string{color:#4d99bf}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}table{border-top:1px solid#ccc;border-left:1px solid#ccc}table td,table th{border-bottom:1px solid#ccc;border-right:1px solid#ccc;padding:3px 5px}table th{border-bottom:2px solid#ccc;text-align:center}blockquote{display:block;border-left:8px solid#d0e5f2;padding:5px 10px;margin:10px 0;line-height:1.4;font-size:100%;background-color:#f1f1f1}code{display:inline-block;*display:inline;*zoom:1;background-color:#f1f1f1;border-radius:3px;padding:3px 5px;margin:0 3px}pre code{display:block}ul,ol{margin:10px 0 10px 20px}</style></head><body>[replace]</body></html>";

        public MainWin()
        {
            InitializeComponent();
            InitializeChromium();
        }
        
        public void InitializeChromium()
        {
            CefSettings settings = new CefSettings();
            //禁用GPU，消除黑边，但是H5动画会比较卡
            settings.CefCommandLineArgs.Add("disable-gpu", "1");
            CefSharpSettings.ShutdownOnExit = true;
            // Initialize cef with the provided settings
            Cef.Initialize(settings);
            // Create a browser component
            string htmlFile = $"{Application.StartupPath}\\HtmlEditor\\index.html";
            chromeBrowser = new ChromiumWebBrowser(htmlFile);
            // Add it to the form and fill it to the form window.
            this.panelBrowser.Controls.Add(chromeBrowser);
            chromeBrowser.Dock = DockStyle.Fill;

            Application.ApplicationExit += Application_ApplicationExit;
        }

        private void Application_ApplicationExit(object sender, EventArgs e)
        {
            Cef.Shutdown();
        }

        private void panelBrowser_SizeChanged(object sender, EventArgs e)
        {
            if (chromeBrowser != null)
            {
                
            }
        }

        private void tabParent_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabParent.SelectedTab == tabSource)
            {
                var task = chromeBrowser.GetBrowser().MainFrame.EvaluateScriptAsync("getHtml();", null);

                task.ContinueWith(t =>
                {
                    if (!t.IsFaulted)
                    {
                        JavascriptResponse response = t.Result;
                        if(response.Success && response.Result != null)
                        {
                            string htmlStr = response.Result.ToString();
                            tbSource.Text = htmlStr;
                        }
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            var task = chromeBrowser.GetBrowser().MainFrame.EvaluateScriptAsync("getHtml();", null);

            task.ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    JavascriptResponse response = t.Result;
                    if (response.Success && response.Result != null)
                    {
                        string htmlStr = response.Result.ToString();
                        string html = HtmlTemplate.Replace(@"[replace]", htmlStr);
                        SaveFileDialog saveFileDialog = new SaveFileDialog();
                        saveFileDialog.Filter = "html(*.html)|*.html|所有文件|*.*";
                        saveFileDialog.DefaultExt = "html";
                        saveFileDialog.AddExtension = true;
                        if (saveFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            string fileName = saveFileDialog.FileName;
                            using (StreamWriter writer = new StreamWriter(fileName))
                            {
                                writer.Write(html);
                                writer.Flush();
                                writer.Close();
                            }
                        }
                        
                    }
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
    }
}
